package com.learn.dict.handler.dictdata;

import cn.hutool.cache.Cache;
import cn.hutool.core.collection.ListUtil;
import com.learn.dict.domain.vo.DictDataOptions;
import com.learn.dict.domain.vo.DictTypeOptions;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 功能描述: 字典表加载 <br/>
 *
 * @author: MI
 * @email: 448341911@qq.com
 * @createDate: 2023/10/22 22:35
 * @updateUser: MI
 * @updateDate: 2023/10/22 22:35
 * @updateRemark: 修改内容
 * @version: v1.0
 */
public abstract class AbstractDictDataHandler implements IDictDataHandler {

    /**
     * 定义分页每页大小
     */
    private static final int PAGE_SIZE = 50;

    @Override
    public void loadDictCache(Collection<DictTypeOptions> dictTypeList, Cache<String, List<DictDataOptions>> cacheData) {
        Set<DictTypeOptions> dictTypeOptionsSet = getDictTypeList();
        dictTypeList.addAll(dictTypeOptionsSet);
        List<String> typeCodeList = dictTypeOptionsSet.stream().map(DictTypeOptions::getTypeCode).collect(Collectors.toList());
        int total = typeCodeList.size() / PAGE_SIZE + 1;

        // 分页加载字典数据
        for (int i = 0; i < total; i++) {
            List<DictDataOptions> dictDataList = getDictDataOptions(ListUtil.page(i, PAGE_SIZE, typeCodeList));
            for (DictDataOptions dictData : dictDataList) {
                if (cacheData.get(dictData.getTypeCode()) == null) {
                    cacheData.put(dictData.getTypeCode(), ListUtil.list(Boolean.FALSE));
                }
                cacheData.get(dictData.getTypeCode()).add(dictData);
            }
        }
    }
}
